package com.dream.myqiyi.ui;

import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.Toast;

import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.GeoPoint;
import com.baidu.mapapi.ItemizedOverlay;
import com.baidu.mapapi.LocationListener;
import com.baidu.mapapi.MKAddrInfo;
import com.baidu.mapapi.MKBusLineResult;
import com.baidu.mapapi.MKDrivingRouteResult;
import com.baidu.mapapi.MKGeneralListener;
import com.baidu.mapapi.MKPoiResult;
import com.baidu.mapapi.MKSearch;
import com.baidu.mapapi.MKSearchListener;
import com.baidu.mapapi.MKSuggestionResult;
import com.baidu.mapapi.MKTransitRouteResult;
import com.baidu.mapapi.MKWalkingRouteResult;
import com.baidu.mapapi.MapActivity;
import com.baidu.mapapi.MapController;
import com.baidu.mapapi.MapView;
import com.baidu.mapapi.MyLocationOverlay;
import com.baidu.mapapi.OverlayItem;
import com.baidu.mapapi.PoiOverlay;
import com.dream.myqiyi.Global;
import com.dream.myqiyi.R;
import com.dream.myqiyi.image.util.ScreenShot;

public class BMapAddressView  extends MapActivity {
	//添加百度地图的相关控件
	private MapView mapView;
	//加载地图的引擎
	private BMapManager bMapManager;
	private MKSearch mSearch = null;
	//在百度地图上添加一些控件,比如是放大或者缩小的控件
	private MapController mapController;
	//定位图层
	MyLocationOverlay mLocationOverlay = null;
	//onResume时注册此listener，onPause时需要Remove
	LocationListener mLocationListener = null;
	private ImageButton searchBtn;
	private Button locationBtn;
	private Button captureBtn;
	private Button cancelBtn;
	private AutoCompleteTextView addressEditText;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.bmap_address_view);
        mapView = (MapView) this.findViewById(R.id.bmapView);
        bMapManager = new BMapManager(BMapAddressView.this	);
        //必须要加载key
        bMapManager.init(Global.BMAP_KEY, new MKGeneralListener() {

			public void onGetPermissionState(int arg0) {
				if(arg0==300){
					Toast.makeText(BMapAddressView.this, "输入的key有错，请核实！！", Toast.LENGTH_SHORT).show();
				}
			}

			public void onGetNetworkState(int arg0) {

			}
		});
        this.initMapActivity(bMapManager);
        //表示可以设置缩放功能
        mapView.setBuiltInZoomControls(true);
        mapController = mapView.getController();
        //设置缩放级别是12个级别
        mapController.setZoom(12);

        Drawable drawable = getResources().getDrawable(R.drawable.bmap_mark_a);
        mapView.getOverlays().add(new MyOverLayItem(drawable));

		// 添加定位图层
        mLocationOverlay = new MyLocationOverlay(this, mapView);
        mapView.getOverlays().add(mLocationOverlay);

        // 注册定位事件
        mLocationListener = new LocationListener() {

			@Override
			public void onLocationChanged(Location location) {
				if (location != null){
					GeoPoint pt = new GeoPoint((int)(location.getLatitude()*1e6),
											   (int)(location.getLongitude()*1e6));
					mapController.animateTo(pt);
				}
			}
        };

        // 初始化搜索模块，注册事件监听
        mSearch = new MKSearch();
        mSearch.init(bMapManager, new MKSearchListener(){

			public void onGetPoiResult(MKPoiResult res, int type, int error) {
				// 错误号可参考MKEvent中的定义
				if (error != 0 || res == null) {
					Toast.makeText(BMapAddressView.this, "抱歉，未找到结果", Toast.LENGTH_LONG).show();
					return;
				}
			    // 将地图移动到第一个POI中心点
			    if (res.getCurrentNumPois() > 0) {
				    // 将poi结果显示到地图上
					PoiOverlay poiOverlay = new PoiOverlay(BMapAddressView.this, mapView);
					poiOverlay.setData(res.getAllPoi());
					mapView.getOverlays().clear();
					mapView.getOverlays().add(poiOverlay);
					mapView.invalidate();
					mapView.getController().animateTo(res.getPoi(0).pt);
			    } else if (res.getCityListNum() > 0) {
			    	String strInfo = "在";
			    	for (int i = 0; i < res.getCityListNum(); i++) {
			    		strInfo += res.getCityListInfo(i).city;
			    		strInfo += ",";
			    	}
			    	strInfo += "找到结果";
					Toast.makeText(BMapAddressView.this, strInfo, Toast.LENGTH_LONG).show();
			    }
			}
			public void onGetDrivingRouteResult(MKDrivingRouteResult res,
					int error) {
			}
			public void onGetTransitRouteResult(MKTransitRouteResult res,
					int error) {
			}
			public void onGetWalkingRouteResult(MKWalkingRouteResult res,
					int error) {
			}
			public void onGetAddrResult(MKAddrInfo res, int error) {
			}
			@Override
			public void onGetBusDetailResult(MKBusLineResult arg0, int arg1) {
				// TODO Auto-generated method stub

			}
			@Override
			public void onGetRGCShareUrlResult(String arg0, int arg1) {
				// TODO Auto-generated method stub

			}
			@Override
			public void onGetSuggestionResult(MKSuggestionResult arg0, int arg1) {
				// TODO Auto-generated method stub

			}

        });

        // 设定搜索按钮的响应
        addressEditText =  (AutoCompleteTextView) findViewById(R.id.AddressText);
    	searchBtn = (ImageButton)findViewById(R.id.SearchBtn);
    	searchBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				mSearch.suggestionSearch(addressEditText.getText().toString());
			}

    	});
    	locationBtn = (Button)findViewById(R.id.LocationButton);;
    	locationBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub

			}

    	});
    	captureBtn = (Button)findViewById(R.id.CaptureButton);;
    	captureBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				String webImageFile = getWebFileName();
				ScreenShot.shootView(mapView, webImageFile);

				Intent intent = new Intent(BMapAddressView.this, NoteViewActivity.class);
				Bundle newBundle = new Bundle();
				newBundle.putString("map_result", "selected");
				newBundle.putString("map_file", webImageFile);
				intent.putExtras(newBundle);
				BMapAddressView.this.setResult(NoteViewActivity.MAP_IMAGE_RESULT, intent);
				BMapAddressView.this.finish();
			}

    	});
    	cancelBtn = (Button)findViewById(R.id.CancelButton);;
    	cancelBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				Intent intent = new Intent(BMapAddressView.this, NoteViewActivity.class);
				Bundle bundle = new Bundle();
				bundle.putString("map_result", "cancel");
				intent.putExtras(bundle);
				BMapAddressView.this.setResult(NoteViewActivity.MAP_IMAGE_RESULT, intent);
				BMapAddressView.this.finish();
			}

    	});

    }

    public class MyOverLayItem extends ItemizedOverlay<OverlayItem>{

    	private List<OverlayItem> list = new ArrayList<OverlayItem>();
    	//以double类型定义一组坐标
    	private double mLat1 = 39.90923;//表示为纬度
    	private double mLon1 = 116.397428;//表示经度

    	private double mLat2 = 39.9022;//表示为纬度
    	private double mLon2 = 116.3922;//表示经度

    	private double mLat3 = 39.9033;//表示为纬度
    	private double mLon3 = 116.3933;//表示经度

    	//用于在地图上标识坐标,用一个图片标注
		public MyOverLayItem(Drawable arg0) {
			super(arg0);
			//第一组数据在地图上的标注点
			GeoPoint geoPoint1  = new GeoPoint((int)(mLat1*1E6),(int)(mLon1*1E6));
			//第二组数据在地图上的标注点
			GeoPoint geoPoint2  = new GeoPoint((int)(mLat2*1E6),(int)(mLon2*1E6));
			//第三组数据在地图上的标注点
			GeoPoint geoPoint3  = new GeoPoint((int)(mLat3*1E6),(int)(mLon3*1E6));
			//标注点,标题,片段
			list.add(new OverlayItem(geoPoint1,"point1","point1"));
			list.add(new OverlayItem(geoPoint2,"point2","point2"));
			list.add(new OverlayItem(geoPoint3,"point3","point3"));
			populate();//实现了地图刷新的功能

		}

		//返回指定的list集合中每一个坐标
		@Override
		protected OverlayItem createItem(int arg0) {
			return list.get(arg0);
		}

		//返回list集合中坐标的个数
		@Override
		public int size() {
			return list.size();
		}

		@Override
		public boolean onTap(int i) {
			Toast.makeText(BMapAddressView.this, list.get(i).getSnippet(), Toast.LENGTH_SHORT).show();
			return true;
		}

    }


    @Override
    protected void onDestroy() {
    	super.onDestroy();
    	if(bMapManager!=null){
    		bMapManager.destroy();
    		bMapManager = null;
    	}
    }

    @Override
    protected void onResume() {
    	super.onResume();
    	if(bMapManager!=null){
    		// 注册定位事件，定位后将地图移动到定位点
    		bMapManager.getLocationManager().requestLocationUpdates(mLocationListener);
            mLocationOverlay.enableMyLocation();
            mLocationOverlay.enableCompass(); // 打开指南针

    		bMapManager.start();
    	}
    }

    @Override
    protected void onPause() {
    	super.onPause();
    	if(bMapManager!=null) {
    		bMapManager.getLocationManager().removeUpdates(mLocationListener);
    		mLocationOverlay.disableMyLocation();
            mLocationOverlay.disableCompass(); // 关闭指南针

    		bMapManager.stop();
    	}
    }

	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}

	private String getWebFileName() {
		return Global.resDir + Global.getGuid() + ".png";
	}

}
